import { Graph, Shape } from '@antv/x6'

/**
 * 创建画布
 * @param options 配置
 * @returns
 */
export function createGraph(options: Partial<Graph.Options>): Graph {
  // 详细配置参见: https://antv-x6.gitee.io/zh/docs/api/graph/graph
  const defaultOptions: Partial<Graph.Options> = {
    width: 800,
    height: 500,
    // 网格背景
    grid: {
      size: 10,
      visible: true
    },
    // 画布拖拽
    panning: {
      enabled: true
    },
    // 对齐线
    snapline: true,
    /**
     * 撤销重做
     * graph.history.undo()
     * graph.history.redo()
     */
    history: true,
    // 剪切板
    clipboard: {
      enabled: true
    },
    // 键盘快捷键
    keyboard: {
      enabled: true
    },
    // 鼠标滚轮缩放 ctrl+滚轮
    mousewheel: {
      enabled: true,
      modifiers: ['ctrl', 'meta'],
      minScale: 0.5,
      maxScale: 2
    },
    // 套索框选 ctrl+鼠标左键
    selecting: {
      enabled: true,
      multiple: true,
      rubberband: true,
      movable: true,
      modifiers: 'ctrl',
      showNodeSelectionBox: true
    },
    /**
     * 连线规则
     * see: https://antv-x6.gitee.io/zh/docs/api/graph/interaction#connecting
     */
    connecting: {
      anchor: 'center',
      connectionPoint: 'anchor',
      allowBlank: false,
      highlight: true,
      snap: true,
      createEdge() {
        return new Shape.Edge({
          attrs: {
            line: {
              stroke: '#5F95FF',
              strokeWidth: 1,
              targetMarker: {
                name: 'classic',
                size: 8
              }
            }
          },
          router: {
            name: 'manhattan'
          }
        })
      },
      validateConnection({
        sourceView,
        targetView,
        sourceMagnet,
        targetMagnet
      }) {
        if (sourceView === targetView) {
          return false
        }
        if (!sourceMagnet) {
          return false
        }
        if (!targetMagnet) {
          return false
        }
        return true
      }
    },
    // 高亮配置
    highlighting: {
      magnetAvailable: {
        name: 'stroke',
        args: {
          padding: 4,
          attrs: {
            strokeWidth: 4,
            stroke: 'rgba(223,234,255)'
          }
        }
      }
    }
  }

  const o = Object.assign({}, defaultOptions, options)
  const graph = new Graph(o)
  return graph
}
